package com.sujeet.learning.soap;

import java.net.URL;
import java.util.Scanner;
import java.util.Vector;
import org.apache.soap.Constants;
import org.apache.soap.Fault;
import org.apache.soap.SOAPException;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.encoding.soapenc.BeanSerializer;
import org.apache.soap.util.xml.QName;

public class CDAdder {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void add(URL url, String title, String artist, String label)
			throws SOAPException {
		System.out.println("Adding CD titled '" + title + "' by '" + artist
				+ "', on the label " + label);
		CD cd = new CD(title, artist, label);
		// Map this type so SOAP can use it
		SOAPMappingRegistry registry = new SOAPMappingRegistry( );
		BeanSerializer serializer = new BeanSerializer( );
		registry.mapTypes(Constants.NS_URI_SOAP_ENC,
				new QName("urn:cd-catalog-demo", "cd"),
				CD.class, serializer, serializer);

		// Build the Call object
		Call call = new Call();
		call.setSOAPMappingRegistry(registry);
		call.setTargetObjectURI("urn:cd-catalog");
		call.setMethodName("addCD");
		call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
		// Set up parameters
		Vector params = new Vector();
		params.addElement(new Parameter("cd", CD.class, cd, null));		
		call.setParams(params);
		// Invoke the call
		Response response;
		response = call.invoke(url, "");
		if (!response.generatedFault()) {
			System.out.println("Successful CD Addition.");
		} else {
			Fault fault = response.getFault();
			System.out.println("Error encountered: " + fault.getFaultString());
		}
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Provide URL. e.g. http://localhost:6464/soap/servlet/rpcrouter\n");
		String urlStr = scanner.nextLine();
		System.out.println("Provide title of CD: \n");
		String title = scanner.nextLine();
		System.out.println("Provide artist of CD: \n");
		String artist = scanner.nextLine();
		System.out.println("Provide label of CD: \n");
		String label = scanner.nextLine();
		try {
			URL url = new URL(urlStr);			
			// Add the CD
			CDAdder adder = new CDAdder();
			adder.add(url, title, artist, label);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
